#include "basic.h"
#include <stdio.h>

__STATIC_INLINE uint32_t GXT_SYSTICK_IsActiveCounterFlag(void)
{
    return ((SysTick->CTRL & SysTick_CTRL_COUNTFLAG_Msk) == (SysTick_CTRL_COUNTFLAG_Msk));
}
uint32_t get_ms()
{
    return get_us() / 1000;
}
uint32_t get_us()
{
    /* Ensure COUNTFLAG is reset by reading SysTick control and status register */
    GXT_SYSTICK_IsActiveCounterFlag();
    uint32_t m = HAL_GetTick();
    const uint32_t tms = SysTick->LOAD + 1;
    uint32_t u = tms - SysTick->VAL;
    if (GXT_SYSTICK_IsActiveCounterFlag())
    {
        m = HAL_GetTick();
        u = tms - SysTick->VAL;
    }
    return (m * 1000 + (u * 1000) / tms);
}

void delay(uint32_t ms)
{
    uint32_t start = get_ms();
    while (get_ms() - start < ms)
        ;
}
void delay_us(uint32_t us)
{
    uint32_t start = get_us();
    while (get_us() - start < us)
        ;
}
